$(function(){

    var total = null;
    var category = null;

    var str = location.search;
    str= str.slice(4);
    var id = +str;

    var page = 1;

    // 渲染导航
    $.ajax({
        url: "http://127.0.0.1:9090/api/getcategorybyid",
        data: {
            categoryid: id
        },
        dataType: "json",
        success:function(result){
            console.log(result);
            $(".cate-nav").html(template("temp-nav",result));
            category = result.result[0].category
        }
    });


    // 渲染商品列表
    function render(page){
        $.ajax({
            url: "http://127.0.0.1:9090/api/getproductlist",
            data: {
                categoryid: id,
                pageid: page || 1
            },
            dataType: "json",
            success: function (result) {
                console.log(result);
                $(".mm-product").html(template("temp-list", result));
                total = Math.ceil(result.totalCount / result.pagesize);
                // text = result.result[0].productName;
                setPage(total,page);
            }
        });
    }
    render();

    // 设置分页
    function setPage(total, page) {
        var str = "";
        for (var i = 1; i <= total; i++) {
            if (i == page) {
                str += "<option slected value='" + i + "'>" + i + "/" + total + "</option>";
            } else {
            }
            str += "<option value='" + i + "'>" + i + "/" + total + "</option>";
        }
        $("select").html(str);
    }

    $(".mm-product").on("click",".item",function(){
        var id = $(this).data("id");
        location.href = "product-details.html?id=" + id + "&cate=" + category;
    });

    $("select").on("change",function(){
        page = $(this).val();
        // $(this).classList.add("selected");
        render(page);
    });

    // 上一页
    $(".prev").on("touchend", function () {
        page--;
        if(page <= 1){
            return;
        }
        render(page);
        window.scrollTo(0,0);
    });
    // 下一页
    $(".next").on("touchend", function () {
        page++;
        if(page >= total){
            return;
        }
        render(page);
        window.scrollTo(0,0);
    });




});